package com.jiejie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiejie.entity.Comments;
import com.jiejie.entity.Likes;
import com.jiejie.mapper.CommentsMapper;
import com.jiejie.mapper.LikesMapper;
import com.jiejie.service.ILikesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.function.ServerResponse;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 辰广
 * @since 2022-10-05
 */
@Service
//@Slf4j
public class LikesServiceImpl implements ILikesService {
    @Autowired
    private LikesMapper likesMapper;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Likes getById(Integer likesId) {
        Likes likes =likesMapper.selectById(likesId);
        return likes;
    }

    @Override
    public int saveLikes(Likes likes) {
        int rows = likesMapper.insert(likes);
        return rows;
    }

    @Override
    public int updateLikes(Likes likes) {
        int rows = likesMapper.updateById(likes);
        return rows;
    }

    @Override
    public int deleteById(Integer likesId) {
        int rows = likesMapper.deleteById(likesId);
        return rows;
    }

    @Override
    public int saveAll(List<Likes> likesList) {
        int rows=0;
        for(int i=0;i<likesList.size();i++){
            likesMapper.insert(likesList.get(i));
            rows++;
        }
        return rows;
    }

    @Override
    public List<Likes> getLikedListByLikedCommentId(Integer LikedCommentId) {
QueryWrapper queryWrapper=new QueryWrapper();
queryWrapper.eq("comments_id",LikedCommentId);

        return likesMapper.selectList(queryWrapper);
    }

    @Override
    public List<Likes> getLikesByCustomer(Integer customerId) {//从数据库查当前用户的点赞
        QueryWrapper<Likes> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("customer_id",customerId);
        List<Likes> likesList=likesMapper.selectList(queryWrapper);
        return likesList;
    }

    @Override
    public Likes getLikesBycomIdAndcustId(Integer comId, Integer CustId) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("comments_id",comId);
        queryWrapper.eq("customer_id",CustId);
        return likesMapper.selectOne(queryWrapper);
    }

    @Override
   // @Transactional
    public void transLikedFromRedisDB() {//根据Redis更新likes表
        List<Likes> likesList=getLikedDataFromRedis();
        for (Likes likes:likesList){
            Likes ls=getLikesBycomIdAndcustId(likes.getCommentsId(),likes.getCustomerId());//从数据库查询符合用户ID和评论ID的点赞记录
            if(ls==null&&likes.getLikesStatus()==0)//数据库没有记录，为0的存入数据库
                saveLikes(likes);
            else
            {
                System.out.println(likes);
                //有记录，看Redis中的数据状态，看看要不要删除
                ls.setLikesStatus(likes.getLikesStatus());
                if(likes.getLikesStatus()==1)//为1的删除，为0的不执行操作
                {
                    deleteById(ls.getLikesId());
                }
            }
        }
    }

    @Override
   // @Transactional
    public void transLikedCountFromRedisDB() {
    List<Comments> commentsList=getLikesNumFromRedis();//这个Comment只有点赞数和commentID两个属性
    for(Comments comments:commentsList){
        Comments comments1=commentsMapper.selectById(comments.getCommentsId());//数据库中的评论
        if(comments1!=null){
            Integer likeNum=comments.getCommentsLikes()+comments1.getCommentsLikes();
            comments1.setCommentsLikes(likeNum);
            //更新评论点赞数
            QueryWrapper<Comments> wrapper=new QueryWrapper<>();
            wrapper.eq("comments_id",comments1.getCommentsId());
            commentsMapper.update(comments1,wrapper);
        }
    }
    }


    //redis
    @Override
    public void saveLikedRedis(Integer likedCustomerId, Integer likedCommentId) {//点赞
        String key="commentUserLike_"+likedCustomerId+"_"+likedCommentId;
        redisTemplate.opsForHash().put("MAP_COMMENT_LIKED",key,0);

    }

    @Override
    public void unlikeFromRedis(Integer likedCustomerId, Integer likedCommentId) {//取消点赞
    String key="commentUserLike_"+likedCustomerId+"_"+likedCommentId;
        redisTemplate.opsForHash().put("MAP_COMMENT_LIKED",key,1);
    }

    @Override
    public void deleteLikedFromRedis(Integer likedCustomerId, Integer likedCommentId) {//删除Redis点赞记录，存入数据库后执行
        String key ="commentUserLike_"+likedCustomerId+"_"+likedCommentId;
        redisTemplate.opsForHash().delete("MAP_COMMENT_LIKED", key);
    }

    @Override
    public void incrementLikeedCount(String likedCommentId) {
        String key="commentUserLike_"+likedCommentId;
        redisTemplate.opsForHash().increment("MAP_COMMENT_LIKED_COUNT",key,1);
    }

    @Override
    public void decrementLikedCount(String likedCommentId) {
        String key="commentUserLike_"+likedCommentId;
        redisTemplate.opsForHash().increment("MAP_COMMENT_LIKED_COUNT",key,-1);
    }

    @Override
    public List<Likes> getLikedDataFromRedis() {//从Redis提取Likes记录
        Cursor<Map.Entry<Object,Object>> cursor=redisTemplate.opsForHash().scan("MAP_COMMENT_LIKED", ScanOptions.NONE);
        List<Likes> likesList=new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object,Object> entry=cursor.next();
            String key=(String) entry.getKey();
            System.out.println("key:"+key);
            String[] split=key.split("_");
            String likedCustomerId=split[1];
            String likedCommentId=split[2];
            System.out.println("Integer.parseInt(likedCustomerId):"+likedCustomerId);
            Integer value=(Integer) entry.getValue();//点赞状态 Redis中的0/1,为0的存入数据库
            //
            Likes likes=new Likes();

            likes.setCustomerId(Integer.parseInt(likedCustomerId));
            likes.setCommentsId(Integer.parseInt(likedCommentId));
            likes.setLikesVersion(0);
            likes.setLikesStatus(value);
            likes.setLikesCreateTime(LocalDateTime.now());
            likes.setLikesUpdateTime(LocalDateTime.now());
            System.out.println("=================="+likes);
            likesList.add(likes);
            redisTemplate.opsForHash().delete("MAP_COMMENT_LIKED",key);
        }
        return likesList;
    }

    @Override
    public List<Comments> getLikesNumFromRedis() {//从redis获取评论的点赞数
        Cursor<Map.Entry<Object,Object>> cursor=redisTemplate.opsForHash().scan("MAP_COMMENT_LIKED_COUNT",ScanOptions.NONE);
        List<Comments> list=new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object,Object> map=cursor.next();
            //将点赞数量存起来
            String key=(String)map.getKey();
            String[] key1=key.split("_");
            String key2=key1[1];//commentId
            Comments comments=new Comments();//只有点赞数和评论id
            comments.setCommentsLikes((Integer)map.getValue());
            comments.setCommentsId(Integer.valueOf(key2));
            list.add(comments);
            //从Redis删除这条记录
            redisTemplate.opsForHash().delete("MAP_COMMENT_LIKED_COUNT",key);
        }
        return list;
    }
    //=========================
    @Override
    public List<Comments> getLikesNumFromRedisFrojsp() {//从redis获取评论的点赞数
        Cursor<Map.Entry<Object,Object>> cursor=redisTemplate.opsForHash().scan("MAP_COMMENT_LIKED_COUNT",ScanOptions.NONE);
        List<Comments> list=new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object,Object> map=cursor.next();
            //将点赞数量存起来
            String key=(String)map.getKey();
            String[] key1=key.split("_");
            String key2=key1[1];//commentId
            Comments comments=new Comments();//只有点赞数和评论id
            comments.setCommentsLikes((Integer)map.getValue());
            comments.setCommentsId(Integer.valueOf(key2));
            list.add(comments);
        }
        return list;
    }

    @Override
    public List<Likes> getLikedDataFromRedisForJsp() {//从Redis提取Likes记录
        Cursor<Map.Entry<Object,Object>> cursor=redisTemplate.opsForHash().scan("MAP_COMMENT_LIKED", ScanOptions.NONE);
        List<Likes> likesList=new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object,Object> entry=cursor.next();
            String key=(String) entry.getKey();
            System.out.println("key:"+key);
            String[] split=key.split("_");
            String likedCustomerId=split[1];
            String likedCommentId=split[2];
            System.out.println("Integer.parseInt(likedCustomerId):"+likedCustomerId);
            Integer value=(Integer) entry.getValue();//点赞状态 Redis中的0/1,为0的存入数据库
            //
            Likes likes=new Likes();

            likes.setCustomerId(Integer.parseInt(likedCustomerId));
            likes.setCommentsId(Integer.parseInt(likedCommentId));
            likes.setLikesVersion(0);
            likes.setLikesStatus(value);
            likes.setLikesCreateTime(LocalDateTime.now());
            likes.setLikesUpdateTime(LocalDateTime.now());
            System.out.println("=================="+likes);
            likesList.add(likes);
        }
        return likesList;
    }}